package com.pactera.madp.cp.handler.sync.impl;

import com.pactera.madp.common.core.util.SpringContextHolder;
import com.pactera.madp.cp.api.dto.sync.SyncDTO;
import com.pactera.madp.cp.api.entity.sync.SyncStateEntity;
import com.pactera.madp.cp.common.annotations.SyncType;
import com.pactera.madp.cp.common.constant.Constants;
import com.pactera.madp.cp.common.enums.sync.SaleServiceEnum;
import com.pactera.madp.cp.common.enums.sync.SyncTypeEnum;
import com.pactera.madp.cp.context.SyncStateContext;
import com.pactera.madp.cp.handler.sync.SyncTypeHandler;
import com.pactera.madp.cp.service.sync.SaleSyncBusinessService;
import com.pactera.madp.cp.service.sync.template.SyncBusinessService;
import com.pactera.madp.cp.service.sync.template.SyncItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executor;

@Slf4j
@Component
@SyncType(SyncTypeEnum.SALE)
public class SaleSyncHandler implements SyncTypeHandler {

    @Override
    public Boolean handler(SyncDTO dto) {
        Executor executor = SpringContextHolder.getBean(Constants.EXECUTOR_PROCESS_NAME);
        SaleServiceEnum[] saleEnums = SaleServiceEnum.values();
        for (SaleServiceEnum saleEnum : saleEnums) {
            executor.execute(() -> {
                // 执行日志信息初始化
                SyncStateEntity syncStateEntity = new SyncStateEntity();
                syncStateEntity.setSyncType(SyncTypeEnum.SALE.getCode());
                syncStateEntity.setSyncSubType(saleEnum.getSubType());
                SyncStateContext.set(syncStateEntity);
                try {
                    // 执行任务
                    ((SyncItemService)SpringContextHolder.getBean(saleEnum.getServiceType())).handler();
                    // 同步数据
                    SyncBusinessService syncBusinessService = SpringContextHolder.getBean(SaleSyncBusinessService.class);
                    syncBusinessService.syncBusiness();
                } finally {
                    SyncStateContext.remove();
                    // 记录执行日志
                    if (syncStateEntity.isSaveLog()) {
                        log.debug("{}{}", saleEnum.getSubType(), "记录任务执行日志");
                        syncStateEntity.insert();
                        log.debug("{}{}", saleEnum.getSubType(), "日志记录成功");
                    }
                }

            });
        }
        return Boolean.TRUE;
    }

}
